package cn.share.life.common.redisson.configure;


import org.apache.commons.lang3.StringUtils;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.redisson.config.SentinelServersConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@ConditionalOnProperty(prefix = "spring.redis", name = "sentinel")
@Configuration
public class RedissonSentinelConfig {


    @Value("${spring.redis.password}")
    private String password;

    @Value("${spring.redis.database}")
    private Integer database;

    @Value("${spring.redis.sentinel.nodes}")
    private String[] sentinelNodes;
    @Value("${spring.redis.sentinel.master}")
    private String sentinelMaster;

    @Value("${spring.redis.sentinel.password}")
    private String sentinelPassword;

    @Bean(name = "redissonClient", destroyMethod = "shutdown")
    public RedissonClient redissonSentinelClient() {
        String[] nodes = new String[sentinelNodes.length];
        for (int i = 0; i < sentinelNodes.length; i++) {
            nodes[i] = "redis://" + sentinelNodes[i];
        }
        // 1、创建配置
        Config config = new Config();

        SentinelServersConfig serverConfig = config.useSentinelServers().addSentinelAddress(nodes)
                .setMasterName(sentinelMaster);
        if (database != null) {
            serverConfig.setDatabase(database);
        }
        if (StringUtils.isNotBlank(password)) {
            serverConfig.setPassword(password);
        }
        if (StringUtils.isNotBlank(sentinelPassword)) {
            serverConfig.setSentinelPassword(sentinelPassword);
        }
        return Redisson.create(config);
    }
}
